#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import MySQLdb
import os,shutil
import time

def movefile(srcfile,dstfile):
    if not os.path.isfile(srcfile):
        print "%s not exist!"%(srcfile)
    else:
        fpath,fname=os.path.split(dstfile)    #分离文件名和路径
        if not os.path.exists(fpath):
            os.makedirs(fpath)                #创建路径
        shutil.move(srcfile,dstfile)          #移动文件
        print "move %s -> %s"%( srcfile,dstfile)


def getData():
	filePath = '/data1/transferOut/'
	filePath_err = '/data1/error/'
	db = MySQLdb.connect("10.20.3.16", "fkyzkr", "sT6*jA1^dF1+", "datatransfer", charset='utf8' )
	# 使用cursor()方法获取操作游标 
	cursor = db.cursor()

	sql = """ SELECT name,id FROM t_transfer_file_info  where  (hash is null or hash='') and status2='01' and nodeip='10.20.3.3' and create_time>'2020-04-25 19:00:00'  limit 20 """
	sql_gethash = "SELECT hash FROM t_transfer_file_hash where filename='%s'"
	sql_updatehash = "update t_transfer_file_info set hash='%s',hashstatus='%s' where id='%s'"

	try:

		# 使用execute方法执行SQL语句
		cursor.execute(sql)

		# 使用 fetchone() 方法获取一条数据
		#data = cursor.fetchone()

		# 获取所有记录列表
		results = cursor.fetchall()

		for row in results:
			filename=row[0]
			fileid=row[1]
			if os.path.exists(filePath+filename):
				print "filename=%s" % filename
			else:
				cursor.execute(sql_updatehash % ('filenotexists',3,fileid))
				db.commit()
				print "filename=%s no exist" % filename
				continue
			cmd = "sha512sum "+ filePath+filename + " |awk '{print $1}'"
			p = os.popen(cmd)
			hashOut = p.read().replace('\n','')
			p.close

			cursor.execute(sql_gethash % filename)
			r = cursor.fetchone()
			if (r is not None) and len(r) > 0:
				hashIn = r[0]
			else:
				hashIn = ''
			#print type(hashIn)
			#print type(hashOut)
			if hashOut == hashIn:
				#print '1=1'
				cursor.execute(sql_updatehash % (hashOut,1,fileid))
				db.commit()
			else:
				#print '1=2'
				cursor.execute(sql_updatehash % (hashOut,2,fileid))
				db.commit()
				movefile(filePath+filename, filePath_err+filename)
			#print "filename=%s,filesha512=%s" % (filename,ss)
			#print "filename=%s,id=%s" % (filename,fileid)
	except Exception as e:
		print e.args
		print "====="
		print e
		db.rollback()
	# 关闭数据库连接
	db.close()
def main():
	#print 'this message is from main function'
	getData()

def createTbale():
	# 创建数据表SQL语句
	sql = """CREATE TABLE t_transfer_file_hash (
	         filename  VARCHAR(200) NOT NULL,
	         hash  VARCHAR(600)
	          )"""
	cursor = db.cursor()
	cursor.execute(sql)



if __name__ == '__main__':
    #createTbale()
    while True:
    	main()
    	time.sleep(30)
